package com.example.getfollowlist

import android.content.Intent
import android.os.Bundle
import android.provider.Settings
import android.widget.Button
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import com.example.getfollowlist.service.AutoClickService

/**
 * 主活动类
 * 
 * 负责应用程序的主界面展示和用户交互。主要功能包括：
 * 1. 检查无障碍服务是否启用
 * 2. 启动无障碍服务
 * 3. 处理用户点击事件
 */
class MainActivity : AppCompatActivity() {
    companion object {
        private const val TAG = "GetFollowList"
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_main)
        
        // 设置窗口边距，确保内容不被系统栏遮挡
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        // 初始化开始按钮并设置点击监听器
        val startButton = findViewById<Button>(R.id.startButton)
        startButton.setOnClickListener {
            if (!isAccessibilityServiceEnabled()) {
                // 如果无障碍服务未启用，跳转到系统设置页面
                startActivity(Intent(Settings.ACTION_ACCESSIBILITY_SETTINGS))
                Toast.makeText(this, "请开启无障碍服务", Toast.LENGTH_LONG).show()
            } else {
                // 如果无障碍服务已启用，启动自动点击服务
                val intent = Intent(this, AutoClickService::class.java).apply {
                    action = AutoClickService.ACTION_START_SERVICE
                }
                startService(intent)
                Toast.makeText(this, "开始自动操作", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 检查无障碍服务是否已启用
     * 
     * @return Boolean 如果无障碍服务已启用返回true，否则返回false
     */
    private fun isAccessibilityServiceEnabled(): Boolean {
        // 构建完整的服务名称
        val serviceName = packageName + "/" + AutoClickService::class.java.canonicalName
        
        // 检查无障碍服务总开关是否打开
        val accessibilityEnabled = Settings.Secure.getInt(
            contentResolver,
            Settings.Secure.ACCESSIBILITY_ENABLED, 0
        )
        
        // 获取已启用的无障碍服务列表
        val serviceString = Settings.Secure.getString(
            contentResolver,
            Settings.Secure.ENABLED_ACCESSIBILITY_SERVICES
        )
        
        // 检查总开关是否打开（值为1）且服务列表中包含本应用的服务
        return accessibilityEnabled == 1 && serviceString?.contains(serviceName) == true
    }
}